import React,{useEffect,useMemo} from 'react'
import {useDispatch,useSelector} from 'react-redux'
import './ShopcartList.css'
import {Button} from 'antd'
export default function ShopCartList() {
  const dispatch=useDispatch()
  useEffect(()=>{
    dispatch({type:'getShopCartListAsync'})
  },[])
  const list=useSelector((state)=>{
     console.log(state.shopcartList);
     return state.shopcartList
  })
  const total=useMemo(()=>{
   return list.filter(item=>item.checked).reduce((pre,cur)=>pre+cur.price*cur.num,0)
  },[list])
  //改变购物车数量的方法
  const changeNum=(_id,n)=>{
    dispatch({
      type:'changeNumAsync',
      _id,
      n
    })
  }
  //勾选或者取消勾选复选框
  const checkedItem=(_id)=>{
    dispatch({type:'checkedItemAsync',_id})
  }
  return (
    <div>
        <h2>购物车列表</h2>
        <Button type='primary'>按钮</Button>
        <table>
           <thead>
              <tr>
                <td>序号</td>
                <td>商品名</td>
                <td>单价</td>
                <td>数量</td>
                <td>小计</td>
              </tr>
           </thead>
           <tbody>
              {
                list.map((item,index)=><tr key={item._id}>
                  <td>
                     <input type="checkbox" checked={item.checked} onChange={()=>checkedItem(item._id)}/>
                  </td>
                  <td>{item.name}</td>
                  <td>{item.price}</td>
                  <td>
                    <button onClick={()=>{changeNum(item._id,-1)}}>-</button>
                    {item.num}
                    <button onClick={()=>{changeNum(item._id,1)}}>+</button>
                  </td>
                  <td>{item.price*item.num}</td>
                </tr>)
              }
              <tr>
                <td colSpan={5}>
                  总价:{total}
                </td>
              </tr>
           </tbody>
        </table>
    </div>
  )
}
